import re
from HTMLParser import HTMLParser

def br2nl(html):
  return re.sub('<br.*?>', '\n', html, flags=re.I)

class MLStripper(HTMLParser):
  """Credit: http://stackoverflow.com/a/925630/784331"""
  def __init__(self):
      self.reset()
      self.fed = []
  def handle_data(self, d):
      self.fed.append(d)
  def get_data(self):
      return self.fed
  def get_html(self):
      return ''.join(self.get_data())

def strip_tags(html):
  """Credit: http://stackoverflow.com/a/925630/784331"""
  s = MLStripper()
  s.feed(html)
  return s.get_html()

html2plain = lambda html: strip_tags(br2nl(html))

#this is a hack, which is not markup-safe; it's best not to use incorrect tag names at all
def delete_invalid_xml_tags(string):
  string = re.sub(r'<(_[^>]+)>.*?</\1>', '', string)
  string = re.sub(r'<_[^>]+/\s*>', '', string)
  return string